#include "head/global.h"

#include <QString>
#include <random>
#include <QRegularExpression>
#include <QDebug>

namespace global
{
const char randomtable[60] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                              'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                              'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
                              'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
                              'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
                              'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X'};

QString getRandomString(int entropy, int sizeOfLine)
{
    QString random_value;
    if(entropy <= 0 || entropy > 59)  entropy = 59;

    std::random_device rd;
    std::uniform_int_distribution<int> dist(0, entropy);

    while(random_value.size() < sizeOfLine) {
        random_value += randomtable[dist(rd)];
    }

    return random_value;
}

QString getValue(const QString &string, const QString &key, Type type)
{
    if (key.isEmpty())
        return QString();

    if (type == eHttpHeader) {
        if (string.indexOf(QRegularExpression(key + ":")) == -1) {
            return QString();
        }
    }
    else if (string.indexOf(QRegularExpression(key + "\\s*=")) == -1) {
        return QString();
    }

    QString result {string};
    if (type == eHttpHeader) {
        result.remove(QRegularExpression("^.*"+key+":\\s", QRegularExpression::DotMatchesEverythingOption));
    }
    else {
        result.remove(QRegularExpression("^.*"+key+"\\s*=", QRegularExpression::DotMatchesEverythingOption));
    }

    QString separator {'\n'};
    if (type == eForTriggers) {
        separator = ":::";
    } else if (type == eForWeb) {
        separator = '&';
    } else if (type == eHttpHeader) {
        separator = "\r\n";
    }

    int valueEnd = result.indexOf(separator);
    if (valueEnd != -1) {
        result.remove(valueEnd, result.size()-valueEnd);
    }
    else if (valueEnd == -1 and type == eForWeb) {
        separator = ' ';
        valueEnd = result.indexOf(separator);
        if (valueEnd != -1) {
            result.remove(valueEnd, result.size()-valueEnd);
        }
    }

    if (type == eForWeb) {
        result = QByteArray::fromPercentEncoding(result.toUtf8());
        result.replace('+', ' ');
    }
    else if (type == eHttpHeader) {
        result.remove('\"');
    }
    else {
        std::string stdResult {result.toStdString()};
        while (stdResult.front() == ' ') stdResult = stdResult.substr(1);
        while (stdResult.back() == ' ') stdResult.pop_back();
        return stdResult.c_str();
    }
    return result;
}

QString toLowerAndNoSpaces(const QString &channelName)
{
    QString result {channelName};
    result.replace(' ', '_');
    result = result.toLower();
    return result;
}
} // namespace
